<template>
  <div class="meeting-statistics-container">
    <!-- 标题与操作按钮 -->
    <div class="header">
      <h2 class="module-title">会议统计子模块</h2>
      <el-button type="primary">洪涝数据</el-button>
    </div>

    <!-- 统计类型标签 -->
    <el-radio-group v-model="selectedStatType" class="stat-type-radio" @change="fetchStatistics">
      <el-radio :value="'month'" label="month">月度统计</el-radio>
      <el-radio :value="'quarter'" label="quarter" style="margin-left: 20px;">季度统计</el-radio>
      <el-radio :value="'year'" label="year" style="margin-left: 20px;">年度统计</el-radio>
    </el-radio-group>

    <!-- 统计卡片区域 -->
    <div class="stat-cards">
      <el-card class="stat-card" shadow="hover">
        <div slot="header">
          总会议数
        </div>
        <div class="card-value">{{ statistics.totalMeetings || 0 }}</div>
        <div class="card-unit">单位/场</div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
          <div slot="header">
            会议室使用率
          </div>
          <div class="card-value">{{ statistics.roomUsageRate || 0 }}%</div>
          <div class="card-unit">单位 %</div>
          <div class="rate-circle">
            <!-- 修正为roomUsageRate -->
            <div class="circle" :style="{ background: `conic-gradient(#67c23a ${(statistics.roomUsageRate || 0)} * 3.6deg, #e9ecef 0deg)` }"></div>
          </div>
      </el-card>
      <!-- 修复后：全勤参会人数卡片 -->
      <el-card class="stat-card" shadow="hover">
        <div slot="header">全勤参会人数</div>
        <div class="card-value">{{ statistics.fullAttendancePeople || 0 }}</div> <!-- 用新增的人数字段 -->
        <div class="card-unit">人/场</div>
      </el-card>

      <!-- 保留：全勤会议占比卡片（正确） -->
      <el-card class="stat-card" shadow="hover">
        <div slot="header">全勤会议占比</div>
        <div class="card-value">{{ statistics.fullAttendanceRate || 0 }}%</div>
        <div class="card-unit">占总会议数比例</div>
      </el-card>
    </div>

    <!-- 数据概览图表区域 -->
      <div class="data-overview">
        <div class="overview-header">
          <h3>数据概览 / {{ getPeriodText }}</h3>
          <el-button type="danger" icon="el-icon-video-pause" circle></el-button>
        </div>
        <div class="chart-container">
          <!-- 图表显示优化：数据为空时显示提示 -->
        <v-chart 
          v-if="statistics.chartData && statistics.chartData.length > 0" 
          :options="chartOptions"
        ></v-chart>
        <div v-else class="no-data">
          <el-icon :size="40" color="#ccc"><Document /></el-icon>
          <p>暂无趋势数据，请选择其他统计周期或检查数据</p>
        </div>
        </div>
      </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElIcon, ElMessage } from 'element-plus';
import { Warning } from '@element-plus/icons-vue';
import request from '@/api/request'; // 统一请求工具路径（与insert.vue保持一致）

// 图表配置（保持不变）
const chartOptions = computed(() => {
  const chartData = statistics.value.chartData || [];
  return {
    xAxis: { 
      type: 'category', 
      data: chartData.map(d => d.period) || []
    },
    yAxis: { type: 'value' },
    series: [{ 
      data: chartData.map(d => d.meetingCount) || [], 
      type: 'line',
      markPoint: { data: [{ type: 'max', name: '最大值' }, { type: 'min', name: '最小值' }] }
    }],
    tooltip: { trigger: 'axis' }
  };
});

const selectedStatType = ref('quarter');
const statistics = ref({
  totalMeetings: 0,
  roomUsageRate: 0,
  fullAttendanceRate: 0,
  overdueMeetings: 0,
  fullAttendancePeople: 0,
  chartData: []
});

// 修正周期文本
const getPeriodText = computed(() => {
  switch(selectedStatType.value) {
    case 'month': return '月度';
    case 'quarter': return '季度';
    case 'year': return '年度';
    default: return '月度';
  }
});
// 修改为与insert.vue一致的请求格式（使用对象配置方式）
const fetchTrendData = async () => {
  try {
    const response = await request({
      method: 'get',
      url: '/meeting/statistics/trend',
      params: { statType: selectedStatType.value }
    });

    if (Array.isArray(response)) {
      statistics.value.chartData = response;
    } else if (response.data && Array.isArray(response.data)) {
      statistics.value.chartData = response.data;
    } else {
      throw new Error('趋势数据非数组格式');
    }
  } catch (error) {
    console.error('获取趋势数据失败：', error.message);
    statistics.value.chartData = [];
    ElMessage.error(`获取趋势数据失败：${error.message || '未知错误'}`);
  }
};

const fetchCoreStatistics = async () => {
  try {
    const response = await request({
      method: 'get',
      url: '/meeting/statistics/overview',
      params: { statType: selectedStatType.value }
    });

    const statData = response.data || response;
    const {
      roomUsageRate = 0,
      fullAttendanceRate = 0,
      ...restData
    } = statData || {};

    statistics.value = {
      ...statistics.value,
      ...restData,
      roomUsageRate: Number(roomUsageRate.toFixed(1)),
      fullAttendanceRate: Number(fullAttendanceRate.toFixed(1))
    };
  } catch (error) {
    console.error('获取核心统计数据失败：', error.message);
    ElMessage.error('获取统计数据失败');
    statistics.value = {
      totalMeetings: 0,
      roomUsageRate: 0,
      fullAttendanceRate: 0,
      overdueMeetings: 0,
      fullAttendancePeople: 0,
      chartData: []
    };
  }
};

const fetchStatistics = async () => {
  await Promise.all([fetchCoreStatistics(), fetchTrendData()]);
};

onMounted(() => {
  fetchStatistics();
});
</script>

<style scoped>
/* 样式部分保持不变 */
.meeting-statistics-container {
  padding: 20px;
  background-color: #f4f4f4;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.module-title {
  font-size: 20px;
  font-weight: bold;
  margin: 0;
}

.stat-type-radio {
  margin-bottom: 20px;
}

.stat-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  width: calc(25% - 20px);
  min-width: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0 5px 0;
}

.card-unit {
  font-size: 14px;
  color: #999;
}

.rate-circle {
  width: 60px;
  height: 60px;
  margin-top: 10px;
}

.circle {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.warning-icon {
  margin-top: 10px;
}

.data-overview {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

.overview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 200px;
}

.mock-chart {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.no-data {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  background-color: #fff;
  border-radius: 8px;
}
</style>